import data.LineLayer;
import data.MyBorderContainer;

import equipments.PB;
import equipments.PU;

import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.events.ContextMenuEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.external.ExternalInterface;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.URLRequest;
import flash.printing.PrintJob;
import flash.printing.PrintJobOptions;
import flash.printing.PrintJobOrientation;
import flash.ui.ContextMenu;
import flash.ui.ContextMenuBuiltInItems;
import flash.ui.ContextMenuItem;
import flash.ui.Mouse;
import flash.utils.Timer;

import flashx.textLayout.elements.ListElement;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.DragSource;
import mx.core.FlexBitmap;
import mx.core.FlexGlobals;
import mx.core.IUIComponent;
import mx.core.IVisualElement;
import mx.core.UIComponent;
import mx.events.CloseEvent;
import mx.events.DragEvent;
import mx.events.FlexEvent;
import mx.events.ListEvent;
import mx.graphics.SolidColor;
import mx.logging.targets.TraceTarget;
import mx.managers.DragManager;
import mx.printing.FlexPrintJob;
import mx.printing.FlexPrintJobScaleType;
import mx.rpc.events.ResultEvent;
import mx.utils.object_proxy;

import net.DoOpenWithAllLoad;
import net.DoSave;
import net.data.Economic;

import spark.components.BorderContainer;
import spark.components.Button;
import spark.components.ComboBox;
import spark.components.Group;
import spark.components.Image;
import spark.components.Scroller;
import spark.core.SpriteVisualElement;
import spark.skins.spark.ErrorSkin;

import util.IconUtility;

private static const FORMAT:String = "box";

private var isCopyBc:Boolean=false;

[Embed(source = 'img/branch/base.jpg')]
public var base_img : Class;
[Embed(source = 'img/tree/BR.jpg')]
public var icon_BR : Class;
[Embed(source = 'img/tree/CE.jpg')]
public var icon_CE : Class;
[Embed(source = 'img/tree/FM.jpg')]
public var icon_FM : Class;
[Embed(source = 'img/tree/PB.jpg')]
public var icon_PB : Class;
[Embed(source = 'img/tree/PU.jpg')]
public var icon_PU : Class;
[Embed(source = 'img/tree/SE.jpg')]
public var icon_SE : Class;

private var treeOpenList:XMLList;

[Bindable]
public static var home:Maros;

public static var selectedItemArr:Array = new Array();

public var changingItem:MyBorderContainer;

public var curItem:MyBorderContainer=null;

//라인긋기를 할때 필요한 bc
private var connectingBc:MyBorderContainer
private var connectingBcLineLayer:LineLayer
private var toConnectingBc:MyBorderContainer

private var mPoint:Point

private var isHit:Boolean=false;

public var linkedArr:ArrayList=new ArrayList();


public var branchArr:ArrayList=new ArrayList();
private var branchIdx:uint=0;

//pb입력받은값
public var pu_num:Number

//더블클릭 여부를 체크하기 위한 변수
private var clickNum:uint;
private var dragTimer:Timer

//아이템 드래그를 위한 변수들
private var initiator:IUIComponent;
private var dragSource:DragSource;
private var dragSourceMouseEvent:MouseEvent;


private var doSave:DoSave

[Bindable]
public var iconImgArr:Array=[];

private var brIconArr:Array=[];
private var eqIconArr:Array=[]; 


//프로젝트 아이디를 받는 변수
public var projectID:String;

//경제성 분석
public var econArr:Array=[];

public var scenaroArr:Array=[];

//현재가 scenario 모드인지 아닌지 판단
public var _isScenarioMode:Boolean=false;
	
private function init():void{
	
	trace("Maros init");
	home=this;	
	iconImgArr=[];
}
	
private function onApplicationComplete():void{
	trace("Maros onApplicationComplete");
		
	dragTimer=new Timer(300);
	dragTimer.addEventListener(TimerEvent.TIMER,dragTimer_hdl);
	
	trace("dragTimer:",dragTimer);
	
	//저장 객체
	projectID = this.loaderInfo.parameters.projectID;
//	projectID = "128";
	doSave = new DoSave(projectID);
	
	//버전관리
	version.text = "2013-04-19 V550"; 
	 
	ro.sendIconImgToFlex();
	
	//아이템에따라 메뉴들의 상태를 변경해주는 메서드
	changeItem("null");
	
	new DoOpenWithAllLoad(projectID);
}

//remote-Objec에 대한 결과를 받는 메서드..
private function ro_resulthandler(e:ResultEvent):void{
	iconImgArr = String(e.result).split(",");
	iconSetting(iconImgArr);
	
	//icon setting 이 끝나고 난 후에 searchBREQWin을 셋팅한다.
	searchBREQWin.iconSetting(brIconArr,eqIconArr);
}



private function iconSetting(_iconArr:Array):void{
	var baseURL:String = "/ram/Admin/System_Img/Upload/";
	var mbc:MyBorderContainer;
	var dotIdx:int;
	for each(var icon:String in _iconArr){
		//					if(icon.indexOf("br_")==-1&&icon.indexOf("eq_")==-1){
		//						continue;
		//					}
		mbc=new MyBorderContainer();
//		trace("이미지로드:",baseURL+icon);
		dotIdx = icon.lastIndexOf(".");
//		trace("dotIdx:",dotIdx);
		mbc.title = icon.substring(0,dotIdx);
//		trace("iconImg:",iconImg);
		mbc.width=70;
		mbc.height=70;
		mbc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
		mbc.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
//		<data:MyBorderContainer id="br1_icon" width="70" height="70" imgUrl="@Embed('img/branch/br1.gif')" title="br1" categori="branch" iName="br" mouseDown="mouseDownHandler(event);" mouseUp="mouseUpHandler(event)"/>
//		<data:MyBorderContainer id="eq1_icon" width="70" height="70" imgUrl="@Embed('img/Eq/eq1.gif')" title="Eq1" categori="eq" iName="eq" mouseDown="mouseDownHandler(event);" mouseUp="mouseUpHandler(event)"/>
		if(icon.indexOf("B_")!=-1){
			trace("br에 넣기");
			brIconArr.push(mbc);
			br_group.addElement(mbc);
			mbc.categori="branch";
			mbc.iName="br"
		}else if(icon.indexOf("E_")!=-1){
			trace("eq에 넣기");
			eqIconArr.push(mbc);
			eq_group.addElement(mbc);
			mbc.categori="eq";
			mbc.iName="eq"
		}
		
//		var urlrq:URLRequest=new URLRequest(baseURL+icon);
		mbc.imgUrl = baseURL+icon;
		
		
		changeItem("null");
	}
}


/*
	상단의 "UP"버튼을 눌렀을때 핸들러 메서드
*/
private function up_bt_hdl(e:MouseEvent):void{
	if(selectedItemArr.length<=0){
		curItem=null;
		return;
	}
	var tempItem:MyBorderContainer
	tempItem= selectedItemArr.pop();
	/*
		만약 현재 curItem이 pu라면 uplevelBc는 pb가 되겠지만..
		모델링상으로는 pb와 pu가 같은 단계에 있으므로..
		pb의 upLevelBc의 뎁스로 가야 한다.
	*/
	if(_isScenarioMode){
		this.removeElement(tempItem.detailViewConForScenario);
		tempItem.detailViewForScenario.removeEventListener(DragEvent.DRAG_ENTER,dragEnterHandler);
		tempItem.detailViewForScenario.removeEventListener(DragEvent.DRAG_DROP,dropHandler);
//		ExternalInterface.call("console.log","curItem.upLeveBc.iName:"+curItem.upLeveBc.iName);
		if(curItem.upLeveBc.iName=="br"){
			_isScenarioMode=false;
			ExternalInterface.call("console.log","시나리오모드종료");
		}
	}else{
		this.removeElement(tempItem.detailViewCon);
		tempItem.detailView.removeEventListener(DragEvent.DRAG_ENTER,dragEnterHandler);
		tempItem.detailView.removeEventListener(DragEvent.DRAG_DROP,dropHandler);
	}
	if(curItem.iName=="pu"){
		curItem = curItem.upLeveBc.upLeveBc;
	}else{
		curItem = curItem.upLeveBc;
	}
	
	if(curItem==null){
		changeItem("default");
		tree.selectedItem=null;
	}else{
		if(_isScenarioMode){
			changeItem("sc");
		}else{
			changeItem(curItem.iName);
		}
		tree.selectedItem=Object(curItem.item);
	}
}

//PB버튼을 눌렀을때는 좀 특별함
public function itemPB_bt_hdl(e:MouseEvent):void{
	wall.visible=true;
	this.setElementIndex(this.wall,this.numElements-1);
	this.setElementIndex(pbNumWin,this.numElements-1);
	pbNumWin.visible=true;
}

public function item_bt_hdl(e:MouseEvent):void{
	//	trace("item_bt_hdl");
	//	trace("e :",e.currentTarget);
	var _type:String = Button(e.currentTarget).id.substring(0,2);
	
	
	item_bt_setting(_type,pu_num);
	
}

/*
	_type : 아이템의 종류 (br, eq,se,ce,pb,sy...)
	_puNum : pb추가시 pu의 갯수;
	isGenerateEq : eq를 생성할때 name과 tagid가 제대로 들어와야지만 정상적으로 생성이 되는데.. 이 두가지가 사용자 입력을 통하여 정상적으로 입력되면
							이 값은 true가 되고.. 아닐때는 false가 된다.
	_bcName : 사용자 입력을 통해 전달받은 bc 의 title
	_bcTag : 사용자 입력을 통해 전달받은 bc의 tagid
*/
public function item_bt_setting(_type:String,_puNum:uint=0,isGenerateEq:Boolean=false,_bcName:String = null, _bcTag:String=null,_itemId:String=null,_initIvest:String=null,_operExpr:String=null,_yearExca:String=null):MyBorderContainer{
	trace("================= Maros.item_bt_setting("+_type, _puNum+") =================");
	
	
	if(_type=="fm"||_type=="sa"||_type=="ca"){
		//엑셀뷰 버튼들                                                
		curItem.addData();
		return null;
	}
	
	if(_type=="eq"&&!isGenerateEq){
		wall.visible=true;
		changeNameWin.dragEvt = null;
		this.setElementIndex(Maros.home.wall,Maros.home.numElements-1);
		this.setElementIndex(Maros.home.changeNameWin,Maros.home.numElements-1);
		changeNameWin.currentState="generateEQ";
		changeNameWin.changeNameIT.text="";
		changeNameWin.changeTagIdIT.text="";
		changeNameWin.visible=true;
		changeNameWin.changeNameIT.setFocus();
		return null;
	}
	
	var bc:MyBorderContainer=new MyBorderContainer();
	bc.width = 70;
	bc.height = 70;
	
	var _item:XML;
	
	//	bc.imgUrl = new base_img();
	if(_type=="br"){
		area.addElement( bc );
		bc.title = "branch";
		bc.categori = "branch";
		bc.iName="br";
		trace("curItem",curItem);
		_bcName=(_bcName==null)?"branch":_bcName;
		_item = new XML("<node label='"+_bcName+"' ename='branch' bc='"+bc+"'/>");
		XML(treeData.node).appendChild(_item);
		bc.item = _item;
		bc.x = 300;
		bc.y = 200;
		branchArr.addItem(bc);
		treeOpenList=tree.openItems as XMLList;
		bc.doubleClickEnabled=true;
		//	bc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
		bc.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
		bc.addEventListener(MouseEvent.DOUBLE_CLICK,bc.detailBt_hdl);
	}else{
		
			
		if(_type=="pb"){
			//			bc.imgUrl = new iconBig_PB();
			bc=curItem.addPB(_puNum,_item,_type);
			//pbDetailViewSetting(bc,pu_num);
		}else{
			var lastGrid:BorderContainer;
			
			//시나리오모드일때
			if(_isScenarioMode){
				bc.idx = curItem.detailArrForScenario.length;
				curItem.detailViewForScenario.addElement( bc );
				bc.tagId = _bcTag;
				bc.title = (bc.title!=null)?bc.title:_type;
				bc.doubleClickEnabled=true;
//				bc.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
				bc.addEventListener(MouseEvent.DOUBLE_CLICK,bc.detailBt_hdl);
//				bc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
				curItem.detailArrPushForScenario(bc);
				lastGrid=BorderContainer(curItem.gridArr.getItemAt(curItem.gridArr.length-1));
				bc.x=lastGrid.x+10;
				bc.y=lastGrid.y+10;
				bc.categori = bc.iName=_type;
				bc.upLeveBc=curItem;
				
				scenaroArr.push(bc);
				ExternalInterface.call("console.log","bc.upLeveBc:"+bc.upLeveBc);
				return bc;
				
			//시나리오모드 아닐때
			}else{
				bc.idx = curItem.detailArr.length;
				curItem.detailView.addElement( bc );
			}
			bc.categori = bc.iName=_type;
			bc.title = _bcName;
			
			if(_type=="eq"){
				bc.tagId = _bcTag;
				
				//초기 투자비
				bc.initInvest = _initIvest;
				
				//운영비
				bc.operExpr = _operExpr;
				
				//교체년수
				bc.yearExca = _yearExca;
				_itemId=(_itemId==null)?bc.itemId:_itemId;
				_item = new XML("<node label='"+bc.title+"("+bc.tagId+")"+"' ename='"+bc.iName+"' bc='"+bc+"' uid='"+_itemId+"'/>");
				
			}else{
				bc.title = (bc.title!=null)?bc.title:_type;
				_item = new XML("<node label='"+bc.title+"' ename='"+bc.iName+"' bc='"+bc+"'/>");
			}
//			trace("==curItem:",curItem);
//			trace("==curItem.detailArr:",curItem.detailArr);
//			trace("==bc:",bc);
			XML(curItem.item).appendChild(_item);
			bc.item = _item;
			var len:uint = curItem.detailArr.length;
			curItem.detailArrPush(bc);
			lastGrid=BorderContainer(curItem.gridArr.getItemAt(curItem.gridArr.length-1));
			bc.x=lastGrid.x+10;
			bc.y=lastGrid.y+10;
			bc.doubleClickEnabled=true;
			//	bc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
			bc.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
			bc.addEventListener(MouseEvent.DOUBLE_CLICK,bc.detailBt_hdl);
		}
	}
	
	bc.upLeveBc=curItem;
//	ExternalInterface.call("console.log","bc.upLevelBc:"+bc.upLeveBc);
	bc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
	openParents(bc.item);
	
	
	return bc;
}

public function mouseDownHandler( evt:MouseEvent ):void
{	
	trace("================= Maros.mouseDownHandler(evt) =================");
	
	var bc:MyBorderContainer=evt.currentTarget as MyBorderContainer;
	
	
	//curItem은 현재 최상위에 선택된 아이템을 뜻한다. curItem이 null이면 현재 최상위 단계에 있다는 말이다.
	if(curItem==null){ 
		if(evt.currentTarget.parent as Group === area){
			trace("카피본");
			isCopyBc=true;
			
//			trace(bc);
//			trace("pBc.length :",bc.pBc.length);
//			trace("nBc.length :",bc.nBc.length);
//			trace("lineLayerArr.length :",bc.lineLayerArr.length);
			
		}else{
			trace("카피본 아님");
			isCopyBc=false;
		}
	}else{
		if(evt.currentTarget.parent as Group === curItem.detailView || evt.currentTarget.parent as Group === curItem.detailViewForScenario){
			trace("카피본"); 
			isCopyBc=true;
		}else{
			trace("카피본 아님");
			isCopyBc=false;
			
			//그리드의 이벤트 리스너를 지움
			var grid:BorderContainer;
			for(var i:uint=0;i<curItem.gridArr.length;++i){
				grid = curItem.gridArr.getItemAt(i) as BorderContainer;
				grid.removeEventListener(DragEvent.DRAG_ENTER, curItem.dragEnter_hdl);
				grid.removeEventListener(DragEvent.DRAG_DROP, curItem.dragDrop_hdl);
			}
		}
	}
	
	initiator = evt.currentTarget as IUIComponent;
	dragSource = new DragSource();
	dragSourceMouseEvent = evt;
	dragTimer.start();
}


public function mouseUpHandler(e:MouseEvent):void{
	trace("mouseUpHandler");  
	dragTimer.stop(); 
	dragTimer.reset();
}

//각 아이템을 누르고 일정시간동안 있으면 드래그가 된다.
private function dragTimer_hdl(event:TimerEvent):void
{
	trace("================= Maros.dragTimer_hdl(event) =================");
	
	dragTimer.reset();
	dragSource.addData( initiator, FORMAT );
	DragManager.doDrag( initiator, dragSource, dragSourceMouseEvent );
	
}



public function dragEnterHandler( evt:DragEvent ):void
{ 
	trace("================= Maros.dragEnterHandler(evt) =================");
	if( evt.dragSource.hasFormat(FORMAT) )
	{
		DragManager.acceptDragDrop( Group( evt.currentTarget ) );
	}
}


/*
	사용자가 branch와 eq를 드래그하여 area에 놓을때 호출
	eve : 마우스로 끌어 놓는 이벤트
	isGenerateEq : 처음 eq를 끌어놓을때는 name과 tagid를 입력하는 창이 뜨게 되고..올바르게 입력되면.. 다시 dropHandler 메서드를 호출하는데.. 이때 true가 된다.
*/
public function dropHandler( evt:DragEvent, isGenerateEq:Boolean=false,_bcName:String=null,_bcTag:String=null,_initIvest:String=null,_operExpr:String=null,_yearExca:String=null):void
{
	trace("================= Maros.dropHandler(evt) =================");
//	ExternalInterface.call("console.log","dropHandler : "+evt+" "+isGenerateEq+" "+_bcName+" "+_bcTag);
	var bcData:MyBorderContainer = (MyBorderContainer)(evt.dragSource.dataForFormat( FORMAT ));
//	trace("bcData",bcData);
//	ExternalInterface.call("console.log","bcData.categori : "+bcData.categori);
//	ExternalInterface.call("console.log","isCopyBc : "+isCopyBc);
	
	
	if(bcData.categori != "branch"){
		isCopyBc=false;
	}
	
	//아이템 그냥 이동 
	if(isCopyBc){
		isCopyBc=false;
		
		if(bcData.categori=="branch"){
			bcData.x = evt.localX-(bcData.width/2);
			bcData.y = evt.localY-(bcData.height/2);
		}else{
			//TODO::그리드와 히트테스트를 하여. 해당 그리드에 아이템을 위치시키고..detailArr를 수정하여 나머지 아이템들도 위치수정
			
		}
		
		//링크줄 다시 연결 - 기존의 lineLayer 들을 다시 그려준다.
		
		//nBc선 다시 긋기
		var z:uint=0;
		var pbcLineLayers:Vector.<LineLayer> = bcData.getLineLayer_InPBC();
		trace("pbcLineLayers",pbcLineLayers.length);
		for(z=0;z<pbcLineLayers.length;++z){
			bendLineDraw(pbcLineLayers[z].startBC,bcData,pbcLineLayers[z],true);
		}
		
		//nBc선 다시 긋기
		var nbcLineLayers:Vector.<LineLayer> = bcData.getLineLayer_InNBC();
		trace("nbcLineLayers",nbcLineLayers.length);
		for(z=0;z<nbcLineLayers.length;++z){
			bendLineDraw(bcData,nbcLineLayers[z].finishBC,nbcLineLayers[z],true);
		}
		return;
	}
	
	//드래그한 아이템이 eq일 경우에는 drop과 동시에..
	//아이템의 이름과 태그아이디를 입력하도록 한다.
	//만약 이름과 태그아이디를 정상적으로 입력치 아니하면..
	//eq아이템은 생성되지 않는다.
	if(bcData.categori=="eq"&&!isGenerateEq){
		ExternalInterface.call("console.log","eq 생성창 띄우기");
		wall.visible=true;
		this.setElementIndex(Maros.home.wall,Maros.home.numElements-1);
		this.setElementIndex(Maros.home.changeNameWin,Maros.home.numElements-1);
		changeNameWin.currentState="generateEQ";
		changeNameWin.changeNameIT.text="";
		changeNameWin.changeTagIdIT.text="";
		changeNameWin.visible=true;
		changeNameWin.changeNameIT.setFocus();
		changeNameWin.dragEvt = evt;
		return;
	}
	var bc:MyBorderContainer = new MyBorderContainer();
	bc.width = bcData.width;
	bc.height = bcData.height;
	bc.imgUrl = bcData.imgUrl;
	bc.categori = bcData.categori
	bc.iName=bcData.iName;
	
	//drop한 아이템이 eq이고 새로 생성할경우
	// 초기투자비와, 운영비, 교체년수등을 셋팅한다
	//_initIvest:int=0,_operExpr:int=0,_yearExca:int
	bc.initInvest=_initIvest;
	bc.operExpr=_operExpr;
	bc.yearExca=_yearExca;
	
	//evt.currentTarget = curItem
	evt.currentTarget.addElementAt( bc,0 );
	
	//새로운 bc에 이벤트 리스너 등록
	bc.doubleClickEnabled=true;
	bc.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
	bc.addEventListener(MouseEvent.MOUSE_UP,mouseUpHandler);
	bc.addEventListener(MouseEvent.DOUBLE_CLICK,bc.detailBt_hdl);
	
	
	
	
	//트리에 등록
	var _item:XML
	if(bc.categori=="branch"){
		bc.title = bcData.title;
		_item = new XML("<node label='"+bc.title+"' ename='"+bc.categori+"'  bc='"+bc+"'/>");
		bc.x = evt.localX-(bc.width/2);
		bc.y = evt.localY-(bc.height/2);
		XML(treeData.node).appendChild(_item);
		branchArr.addItem(bc);
	}else{
		var len:uint = curItem.detailArr.length;
		var lastGrid:BorderContainer;
		if(_isScenarioMode){
			curItem.detailArrPushForScenario(bc);
			lastGrid=BorderContainer(curItem.gridArr.getItemAt(curItem.gridArr.length-1));
			bc.x=lastGrid.x+10
			bc.y=lastGrid.y+10
			bc.title = _bcName;
			bc.tagId = _bcTag;
			bc.upLeveBc=curItem;
			ExternalInterface.call("console.log","bc.upLeveBc:"+bc.upLeveBc);
			return;
		}
		//detailArr에 push하기
		curItem.detailArrPush(bc);
		lastGrid=BorderContainer(curItem.gridArr.getItemAt(curItem.gridArr.length-1));
		bc.x=lastGrid.x+10
		bc.y=lastGrid.y+10
			
		//bc의 Name을 입력받은 value로 셋한다.
		bc.title = _bcName;
		bc.tagId = _bcTag;
		_item = new XML("<node label='"+bc.title+"("+bc.tagId+")"+"' ename='"+bc.categori+"'  bc='"+bc+"' uid='"+bc.uid+"'/>");
		XML(curItem.item).appendChild(_item);
		
		//그리드의 이벤트 리스너를 다시 준다
		var grid:BorderContainer;
		for(var i:uint=0;i<curItem.gridArr.length;++i){
			grid = curItem.gridArr.getItemAt(i) as BorderContainer;
			grid.addEventListener(DragEvent.DRAG_ENTER, curItem.dragEnter_hdl);
			grid.addEventListener(DragEvent.DRAG_DROP, curItem.dragDrop_hdl);
		}
	}
	bc.item = _item;
	bc.upLeveBc=curItem;
	
	//	tree.openItems = treeData..node;
	
	//	bc.idx = branchIdx;
	//	branchIdx++;
	tree.openItems=[];
	openParents(bc.item);
	//	bc.btSetting();
	
	
}
private function treeInit(e:FlexEvent):void{ 
	trace("init");
	
	tree.openItems = treeData..node;
}
private function treeInit2(e:MouseEvent):void{
	trace("init");
	
	tree.openItems = treeData..node;
}

private function tree_iconFunc(item:Object):String{
	//	trace("================= Maros.tree_iconFunc("+item+") =================");
	var str:String = item.@ename.toString();
	switch(str){
		case "branch":
			tree.setItemIcon(item,icon_BR,icon_BR);
			break;
		case "ce":
			tree.setItemIcon(item,icon_CE,icon_CE);
			break;
		case "fm":
			tree.setItemIcon(item,icon_FM,icon_FM);
			break;
		case "pb":
			tree.setItemIcon(item,icon_PB,icon_PB);
			break;
		case "pu":
			tree.setItemIcon(item,icon_PU,icon_PU);
			break;
		case "se":
			tree.setItemIcon(item,icon_SE,icon_SE);
			break;
		case "eq":
			tree.setItemIcon(item,icon_FM,icon_SE);
			break;
	}
	return item.@label;
}



public function changeItem(_n:String):void{
	ExternalInterface.call("console.log","changeItem : "+_n);
	var brBc:MyBorderContainer;
	var eqBc:MyBorderContainer;
	switch(_n){
		case "br":
			up_bt.enabled=true;
			for each(brBc in brIconArr){
				brBc.enabled=false;
			}
			for each(eqBc in eqIconArr){  
				eqBc.enabled=true;
			}
			br_bt.enabled=false;
			eq_bt.enabled=true;
			se_bt.enabled=true;
//			ce_bt.enabled=true;
			pb_bt.enabled=true;
			sy_bt.enabled=true;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=true;
			break;
		case "eq":
			for each( eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=true;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			up_bt.enabled=true;
			search_bt.enabled=true;
			break;
		case "fm":
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=false;
			break;
		case "se":
			for each(eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=true;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=false;
			break;
		case "sa":
			for each(eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=false;
			break;
		case "ce":
			for each( eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=true;
			pu_bt.enabled=false;
			search_bt.enabled=false;
			break;
		case "ca":
			for each( eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=false;
			break;
		case "pb":
			for each(eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=false;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=true;
			search_bt.enabled=false;
			break;
		case "sy":
		case "pu":
			for each( brBc in brIconArr){
				brBc.enabled=false;
			}
			for each(eqBc in eqIconArr){
				eqBc.enabled=true;
			}
			br_bt.enabled=false;
			eq_bt.enabled=true;
			se_bt.enabled=true;
			pb_bt.enabled=true;
			sy_bt.enabled=true;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			up_bt.enabled=true;
			search_bt.enabled=false;
			break;
		case "sc":	//scenario
			for each( brBc in brIconArr){
				brBc.enabled=false;
			}
			for each(eqBc in eqIconArr){
				eqBc.enabled=true;
			}
			br_bt.enabled=false;
			eq_bt.enabled=true;
			se_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			up_bt.enabled=true;
			search_bt.enabled=false;
			break;
		default:	//제일 상위로
			up_bt.enabled=false;
			for each( brBc in brIconArr){
				brBc.enabled=true;
			}
			for each(eqBc in eqIconArr){
				eqBc.enabled=false;
			}
			br_bt.enabled=true;
			eq_bt.enabled=false;
			se_bt.enabled=false;
			ce_bt.enabled=false;
			pb_bt.enabled=false;
			sy_bt.enabled=false;
			fm_bt.enabled=false;
			sa_bt.enabled=false;
			ca_bt.enabled=false;
			pu_bt.enabled=false;
			search_bt.enabled=true;
			break;
		
		
	}
}

//[Bindable] 
//public function iConImg_hdl(e:MouseEvent):void{
//	trace("MarosSrc.iConImg_hdl(e)");
//	
//	var imgUrl:Object = Image(e.currentTarget).source;
//	
//	if(changingItem.iName=="pb"){
//		var pb:PB=PB(changingItem);
//		var pu:PU
//		for(var i:uint=0;i<pb.detailArr.length;++i){
//			pu=PU(pb.detailArr.getItemAt(i));
//			pu.imgUrl=imgUrl;
//		}
//	}else{
//		changingItem.imgUrl=imgUrl;
//	}
//	
//	wall.visible=false;
//	changeIconWin.visible=false;
//}

//클릭한 아이템의 부모들열기
public function openParents(node:XML):void{
	if(node==null){
		return;
	}
	tree.expandItem(node,true);
	openParents(node.parent());
}

/*트리에서 아이템을 더블클릭시 핸들러*/
private function itemDoubleClickFunc(e:MouseEvent):void{
	trace("================= Maros.itemDoubleClickFunc(e) =================");
	
	trace(e.currentTarget.selectedItem.toXMLString())
	//가장 마지막 . 이후로 나눔
	var item:XML=e.currentTarget.selectedItem as XML;
	
	//pb아이템 더블클릭시에는 아무것도 하지 않는다.
	//pb의 디테일 화면은 없기때문이다.
	if(item.@ename=="pb"){
		return;
	}
	
	
	//선택한 아이템만 열기
	tree.openItems=[];
	openParents(item);
	tree.selectedItem = Object(item); 
	trace("== item ==");
	trace(item.toXMLString());
	trace("== item ==");
	
	if(item.@ename=="root"){
		for(var z:uint=0;z<selectedItemArr.length;++z){
			var dd:Group=selectedItemArr[z].detailView;
			var dd2:BorderContainer=selectedItemArr[z].detailViewCon;
			dd.removeEventListener(DragEvent.DRAG_ENTER,dragEnterHandler);
			dd.removeEventListener(DragEvent.DRAG_DROP,dropHandler);
			this.removeElement(dd2);
		}
		selectedItemArr=[];
		
		curItem=null;
		changeItem("default");
		
		return;
	}
	
	var strr:String=item.@bc.toXMLString();
	var i:uint=0;
	var bc:MyBorderContainer;
	trace("item.@ename:",item.@ename);
	if(item.@ename=="branch"){
		
		//area에서 bc 를 찾는다.
		for(i=0;i<area.numElements;++i){
			trace(area.getElementAt(i));
			if(area.getElementAt(i)==strr){
				trace("찾았다")
				bc=area.getElementAt(i) as MyBorderContainer;
				break;
			}
		}
		
	}else{
		
		//eq를 찾는다.
		for(i=0;i<area.numElements;++i){
			var tt:MyBorderContainer=searchBc(area.getElementAt(i) as MyBorderContainer,strr); 
			if(tt!=null){
				bc=tt;
				break;
			}
		}
	}
	
	//현재 curItem이 bc와 같으면 리턴 (현재 보고 있는 아이템을 tree에서 더블클릭한경우)
	if(curItem==bc)return;
	
	trace("bc.iName:",bc.iName);
	
	if(bc.iName=="branch"){
		bc.dispatchEvent(new MouseEvent(MouseEvent.DOUBLE_CLICK));
	}else{
		
		//==현재 디테일뷰들 모두 삭제
		trace("지우기전,selectedItemArr.length:",selectedItemArr.length);
		for(var j:uint=0;j<selectedItemArr.length;++j){
			var d:BorderContainer=selectedItemArr[j].detailViewCon;
			var d2:Group=selectedItemArr[j].detailView;
			//			selectedItemArr.shift()
			trace("d:",d);
			trace("j:",j);
			d2.removeEventListener(DragEvent.DRAG_ENTER,dragEnterHandler);
			d2.removeEventListener(DragEvent.DRAG_DROP,dropHandler);
			this.removeElement(d);
			//			try{
			//			}catch(e:Error){
			//				trace("ERROR::",e);
			//			}
		}
		trace("지운후,selectedItemArr.length:",selectedItemArr.length);
		selectedItemArr=[];
		
		
		//==
		
		var tempBc:MyBorderContainer=bc;
		var elementsIdx:int = this.numElements-1;
		trace("elementsIdx:",elementsIdx)
		while(tempBc!==null){
//				tempBc가 pb이면.. 무시한다.
				if(tempBc.iName=="pb"){
					tempBc=tempBc.upLeveBc;
					continue;
				}
			this.addElementAt(tempBc.detailViewCon,elementsIdx);
			selectedItemArr.unshift(tempBc);
			tempBc.detailView.addEventListener(DragEvent.DRAG_ENTER,Maros.home.dragEnterHandler);
			tempBc.detailView.addEventListener(DragEvent.DRAG_DROP,Maros.home.dropHandler);
			
			tempBc=tempBc.upLeveBc;
		}
		curItem=bc;
		ExternalInterface.call("console.log","bc.iName : "+bc.iName);
		changeItem(bc.iName);
	}
	ExternalInterface.call("console.log","selectedItemArr : "+selectedItemArr);
	
}

public function connectLine(_bc:MyBorderContainer):void{
	connectingBc=_bc;
//	trace("connectingBc:",connectingBc.name);
	//	connectingBc.btTimer.reset();
	//	connectingBc.timer_hdl();
	//	area.setElementIndex(connectingBc,0);
	//connectingMode
	
	trace("branchArr.length",branchArr.length);
	for(var i:uint=0;i<branchArr.length;++i){
		if(MyBorderContainer(branchArr.getItemAt(i))!=_bc){
			//			MyBorderContainer(branchArr.getItemAt(i)).modeChange("connect");
			MyBorderContainer(branchArr.getItemAt(i)).removeEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
		}
	}
	//	connectingBcLineLayer = connectingBc.createLineLayer();
	this.addEventListener(Event.ENTER_FRAME,connectMoveLine);
	
	
}
private function connectMoveLine(event:Event):void
{
	if(!this.hasEventListener(MouseEvent.CLICK)){
		this.addEventListener(MouseEvent.CLICK,linkClick);
	}
	mPoint = new Point(this.mouseX,this.mouseY);
	connectingBc.graphics.clear();
	
	var inFlag:Boolean=false
	//	trace("x:",area.globalToLocal(mPoint).x,"y:",area.globalToLocal(mPoint).y);
	trace("= for문시작 =");
	for(var i:uint=0;i<branchArr.length;++i){
		if(inFlag){
			break	
		}
		if(MyBorderContainer(branchArr.getItemAt(i))!=connectingBc){
			//			trace(MyBorderContainer(branchArr.getItemAt(i)).name,MyBorderContainer(branchArr.getItemAt(i)).x,MyBorderContainer(branchArr.getItemAt(i)).y);
			
			if(MyBorderContainer(branchArr.getItemAt(i)).hitTestPoint(area.globalToLocal(mPoint).x+310,area.globalToLocal(mPoint).y+159,true)){
				trace("HIT!!!!!");
				isHit=true;
				toConnectingBc=MyBorderContainer(branchArr.getItemAt(i))
				connectingBc.graphics.lineStyle(1,0xff0000);
				inFlag=true;
				break;//<- 안의 포문을 정지
				
			}else{
				trace("NOT HIT!!!!!");
				isHit=false;
				toConnectingBc=null;
				connectingBc.graphics.lineStyle(1);
				
			}
		}else{
			trace("JUMP!!!");
		}
	}
	trace("= for문끝 =");
	connectingBc.graphics.moveTo(35,35);
	connectingBc.graphics.lineTo(connectingBc.globalToLocal(mPoint).x,connectingBc.globalToLocal(mPoint).y);
}

//라인긋
private function linkClick(e:MouseEvent):void{
	trace("linkClick");
	if(isHit){
		
		bendLineDraw(connectingBc,toConnectingBc);
//		connectingBcLineLayer.deleteBt_setting();
		
	}else{
		connectingBc.graphics.clear();
		
		//connectingBcLineLayer삭제
		for(var h:uint=0;h<connectingBc.lineLayerArr.length;++h){
			if(connectingBc.lineLayerArr[h]===connectingBcLineLayer){
				connectingBc.lineLayerArr.splice(h,1);
				break;
			}
		}
	}
	
	this.removeEventListener(Event.ENTER_FRAME,connectMoveLine);
	for(var c:uint=0;c<branchArr.length;++c){
		if(MyBorderContainer(branchArr.getItemAt(c))!=connectingBc){
			//			MyBorderContainer(branchArr.getItemAt(i)).modeChange("normal");
			MyBorderContainer(branchArr.getItemAt(c)).addEventListener(MouseEvent.MOUSE_DOWN,mouseDownHandler);
		}
	}
	this.removeEventListener(MouseEvent.CLICK,linkClick);
}

public function bendLineDraw(_b1:MyBorderContainer,_b2:MyBorderContainer,_b1_lineLayer:LineLayer=null,_justMove:Boolean=false):void{
	trace("bendLineDraw");
	
	_b1.graphics.clear();
	
	if(!_justMove){
		_b1.nBc.push(_b2);
		_b2.pBc.push(_b1);
		linkedArr.addItem(_b1);
	}
	
	
	var ll:LineLayer
	if(_b1_lineLayer==null){
		ll = _b1.createLineLayer();
	}else{
		ll = _b1_lineLayer;
	}
	ll.startBC=_b1;
	ll.finishBC=_b2;
	drawLine(ll);
	
	
	function drawLine(ll:LineLayer):void{
		trace("drawLine");
		trace(_b1);
		trace(_b2);
		trace(ll);
		//		ll.graphics.moveTo(0,0);
		ll.graphics.clear();
		ll.graphics.lineStyle(1,0x0000ff);
		var angle:Number=0;
		
		var xx:Number=70,yy:Number=35;
		ll.graphics.moveTo(xx,yy);		
		
		if((_b1.x+70+20)<_b2.x){
			xx+=(_b2.x-(_b1.x+70))/2;
			ll.graphics.lineTo(xx,yy);		
			yy+=_b2.y-_b1.y;
			ll.graphics.lineTo(xx,yy);		
			xx+=(_b2.x-(_b1.x+70))/2;
			ll.graphics.lineTo(xx,yy);		
		}else{
			if(_b1.y<_b2.y){//_b2 가 _b1 보다 아래있을경우
				xx+=10;
				ll.graphics.lineTo(xx,yy);
				yy+=(_b2.y+70)-(_b1.y+35);
				ll.graphics.lineTo(xx,yy);
				xx-=(_b1.x+80)-(_b2.x-10);
				ll.graphics.lineTo(xx,yy);
				yy-=35;
				ll.graphics.lineTo(xx,yy);
				xx+=10;
				ll.graphics.lineTo(xx,yy);
			}else{	//_b2가 _b1 보다 위에 있을경우
				xx+=10;
				ll.graphics.lineTo(xx,yy);
				yy+=35;
				ll.graphics.lineTo(xx,yy);
				xx-=((_b1.x+80)-(_b2.x-10));
				ll.graphics.lineTo(xx,yy);
				yy-=((_b1.y+70)-(_b2.y+35));
				ll.graphics.lineTo(xx,yy);
				xx+=10;
				ll.graphics.lineTo(xx,yy);
			}
		}
		
		//마지막 화살표 그리기
		//		trace("angle:",angle);
		var x1:Number=xx+(5*Math.cos((angle-150)*(Math.PI/180)))
		var y1:Number=yy+(5*Math.sin((angle-150)*(Math.PI/180)))
		ll.graphics.lineTo(x1,y1)
		ll.graphics.moveTo(xx,yy)
		var x2:Number=xx+(5*Math.cos((angle+150)*(Math.PI/180)))
		var y2:Number=yy+(5*Math.sin((angle+150)*(Math.PI/180)))
		ll.graphics.lineTo(x2,y2)
	}
	
	
}

/*
	_obj에서 ss를 @item으로 가지는 eq를 찾아 리턴하는 메서드.
	_obj :  branch타입.
	ss : _obj에서 찾고자 하는 하위 eq의 xml string.
*/
private function searchBc(_obj:MyBorderContainer,ss:String):MyBorderContainer{
	trace("searchBc");
	trace("obj:",_obj);
	trace("ss:",ss);
	var i:uint;
	var bc:MyBorderContainer;
	trace("length:",_obj.detailArr.length);
	for(i=0;i<_obj.detailArr.length;++i){
		bc = _obj.detailArr.getItemAt(i) as MyBorderContainer
		trace("i:",i);
		trace("bc:",bc)
		trace("sub len:",bc.detailArr.length)
		if(bc.detailArr.length>0){
			var tt:MyBorderContainer=searchBc(bc as MyBorderContainer,ss);
			if(tt!=null){
				return tt;
			}
		}
		
		var dotIdx:int = bc.toString().lastIndexOf(".");
		var dotIdx2:int = ss.toString().lastIndexOf(".");
		trace("dotIdx2:",dotIdx2);
		trace("bc:",bc.toString().substr(dotIdx+1))
		trace("ss:",ss.substr(dotIdx2+1))
		if(dotIdx2==-1){
			if(bc.toString().substr(dotIdx+1) == ss){
				return bc;
			}
			
		}else{
			if(bc.toString().substr(dotIdx+1) == ss.substr(dotIdx2+1)){
				return bc;
			}
		}
		
	}
	trace("ERROR::=========================================="); 
	trace("searchBC에서 리턴값이 null 입니다");
	trace("ERROR::==========================================");
	return null;
}

//뉴메릭스테퍼 확인버튼
private function numIP_w_bt(e:Event):void{
	trace("ns.value:",pbNumWin.ns.value);
	pu_num=pbNumWin.ns.value;
	pb_bt.removeEventListener(MouseEvent.CLICK,itemPB_bt_hdl);
	pb_bt.addEventListener(MouseEvent.CLICK,item_bt_hdl);
	pb_bt.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
	pb_bt.removeEventListener(MouseEvent.CLICK,item_bt_hdl);
	pb_bt.addEventListener(MouseEvent.CLICK,itemPB_bt_hdl);
	numIp_close(new CloseEvent("dm"));
	
}
private function numIp_close(e:CloseEvent):void{
	wall.visible=false;
	pbNumWin.visible=false;
	
}

//pb타입의 아이템 셋팅작업 - detailView에 pu들을 셋팅함
private function pbDetailViewSetting(_bc:MyBorderContainer,_n:Number):void{
	//	trace("pb_setting:",_bc, _n);
	var tempCurItem:MyBorderContainer = curItem;
	curItem=_bc;
	//	_bc.pu_num=_n;
	//	_bc.label.text += "\n block : "+_n;
	//	trace("시작:",curItem.detailView.numElements);
	pu_bt.enabled=true;
	for(var i:uint=0;i<_n;++i){
		pu_bt.dispatchEvent(new MouseEvent(MouseEvent.CLICK));
	}
	pu_bt.enabled=false;
	//	trace("끝:",curItem.detailView.numElements);
	//	trace("pu_num:",_bc.pu_num);
	curItem = tempCurItem;
}


private function scrbChghdl(e:Event):void{
	//	trace(e.currentTarget.id);
	if(e.currentTarget.id=="scrBar"){
		area.y = (area.height-431)/100*-scrBar.value;
		return;		
	}
	if(e.currentTarget.id=="hScrBar"){
		area.x = (area.width-931)/100*-hScrBar.value;
		return;		
	}
}


public function changeIconWin_closeHandler(event:CloseEvent):void
{
	trace("Maros.changeIconWin_closeHandler(event)");
	
	wall.visible=false;
	trace(changeIconWin);
	trace(event.currentTarget);
	event.currentTarget.visible=false;
}

public function onWinCloseHandler(event:CloseEvent):void
{
	trace("Maros.changeNameWin_closeHandler(event)");
	
	wall.visible=false;
	event.currentTarget.visible=false;
	
}

public function pbNumWin_closeHandler(event:CloseEvent):void
{
	trace("Maros.pbNumWin_closeHandler(event)");
	
	wall.visible=false;
	event.currentTarget.visible=false;
}

private function save_bt_hdl(event:MouseEvent):void
{
	doSave.makeSaveItem();
	
}

protected function search_bt_hdl(event:MouseEvent):void
{
	wall.visible=true;
	this.setElementIndex(wall,this.numElements-1);
	if(curItem == null){
		this.setElementIndex(searchBREQWin,this.numElements-1);
		searchBREQWin.currentState="br";
		searchBREQWin.visible=true;
		
		
	}else if(curItem.iName=="br"){
		
		this.setElementIndex(searchBREQWin,this.numElements-1);
		searchBREQWin.currentState="eq";
		searchBREQWin.visible=true;
		
		
	}else{
		this.setElementIndex(searchFMWin,this.numElements-1);
		searchFMWin.visible=true;
	}
}


//print버튼 핸들러
private function print_hdl(e:MouseEvent):void{
	var pj:FlexPrintJob=new FlexPrintJob();
	var printView:Group;
	if(curItem==null){
		printView = area;
		if (pj.start()) {
			try {
				pj.addObject(printView,FlexPrintJobScaleType.SHOW_ALL);
			}catch(e:Error) {
				// handle error 
			}
			pj.send();
		}
	}else{
		if (pj.start()) {
			try {
				var ww:Number = curItem.scrBar.viewport.contentWidth;
				var hh:Number = curItem.scrBar.viewport.contentHeight;
				trace("viewport 때기전 :",curItem.detailView.height);
				curItem.scrBar.viewport=null;
				var con:Group=new Group();
				con.width = ww;
				con.height = hh;
				con.addElement(curItem.detailView);
				this.addElement(con);
		//		trace("con.height : ",con.height);
				
				printView = con;
				pj.addObject(printView,FlexPrintJobScaleType.SHOW_ALL);
				pj.send();
				curItem.detailViewCon.addElement(curItem.detailView);
				curItem.resetScrBar(hh);
				this.removeElement(con);
			}catch(e:Error) {
				this.removeElement(con);
				// handle error 
			}
		}
	}
	
	
}


